package com.dhcc.DRGsHosp.facade.impl;

import java.io.File;
import java.io.FileInputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.InvokeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.MDCGroupApplication;
import com.dhcc.DRGsHosp.core.domain.ADRG;
import com.dhcc.DRGsHosp.core.domain.DRGs;
import com.dhcc.DRGsHosp.core.domain.MDCGroup;
import com.dhcc.DRGsHosp.facade.MDCGroupFacade;
import com.dhcc.DRGsHosp.facade.dto.ADRGDTO;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.dto.MDCGroupDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.ADRGAssembler;
import com.dhcc.DRGsHosp.facade.impl.assembler.IndexCalAssembler;
import com.dhcc.DRGsHosp.facade.impl.assembler.MDCGroupAssembler;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;

@Named("drgsHospFacadeImpl28")
public class MDCGroupFacadeImpl implements MDCGroupFacade {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MDCGroupFacadeImpl.class);
	@Autowired
	private MDCGroupApplication  application;


	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
	
	public InvokeResult getMDCGroup(String mdcCode) {
		return InvokeResult.success(MDCGroupAssembler.toDTO(application.getMDCGroup(mdcCode)));
	}
	
	public InvokeResult creatMDCGroup(MDCGroupDTO mDCGroupDTO) {
		application.creatMDCGroup(MDCGroupAssembler.toEntity(mDCGroupDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult updateMDCGroup(MDCGroupDTO mDCGroupDTO) {
		application.updateMDCGroup(MDCGroupAssembler.toEntity(mDCGroupDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult removeMDCGroup(String mdcCode) {
		application.removeMDCGroup(application.getMDCGroup(mdcCode));
		return InvokeResult.success();
	}
	
	public InvokeResult removeMDCGroups(String[] mdcCodes) {
		Set<MDCGroup> mDCGroups= new HashSet<MDCGroup>();
		for (String mdcCode : mdcCodes) {
			mDCGroups.add(application.getMDCGroup(mdcCode));
		}
		application.removeMDCGroups(mDCGroups);
		return InvokeResult.success();
	}
	
	public List<MDCGroupDTO> findAllMDCGroup() {
		return MDCGroupAssembler.toDTOs(application.findAllMDCGroup());
	}
	
	public Page<MDCGroupDTO> pageQueryMDCGroup(MDCGroupDTO queryVo, int currentPage, int pageSize) {
		List<Object> conditionVals = new ArrayList<Object>();
	   	StringBuilder jpql = new StringBuilder("select _mDCGroup from MDCGroup _mDCGroup   where 1=1 ");
	   	if (queryVo.getMdcCode() != null && !"".equals(queryVo.getMdcCode())) {
	   		jpql.append(" and _mDCGroup.mdcCode like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getMdcCode()));
	   	}		
	   	if (queryVo.getVerCode() != null && !"".equals(queryVo.getVerCode())) {
	   		jpql.append(" and _mDCGroup.verCode like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getVerCode()));
	   	}		
	   	if (queryVo.getMdcDesc() != null && !"".equals(queryVo.getMdcDesc())) {
	   		jpql.append(" and _mDCGroup.mdcDesc like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getMdcDesc()));
	   	}		
        Page<MDCGroup> pages = getQueryChannelService()
		   .createJpqlQuery(jpql.toString())
		   .setParameters(conditionVals)
		   .setPage(currentPage, pageSize)
		   .pagedList();
		   
        return new Page<MDCGroupDTO>(pages.getStart(), pages.getResultCount(),pageSize, MDCGroupAssembler.toDTOs(pages.getData()));
	}

	@Override
	public InvokeResult adrgListByMdc(MDCGroupDTO dto) {
		List<ADRG> adrgGroupList = application.findAdrgByMdcList(MDCGroupAssembler.toEntity(dto));
		return InvokeResult.success(adrgGroupList);
	
	}
	@Override
	public InvokeResult drgListByMdc(MDCGroupDTO dto) {
		
		List<DRGs> drgGroupList = application.findDrgByMdcList(MDCGroupAssembler.toEntity(dto));
		return InvokeResult.success(drgGroupList);
	
	}

	@Override
	public InvokeResult drgListByAdrg(ADRGDTO dto) {
		
		List<DRGs> drgGroupList = application.drgListByAdrg(ADRGAssembler.toEntity(dto));
		return InvokeResult.success(drgGroupList);
	}

	@Override
	public InvokeResult mdcSearch(MDCGroupDTO dto) {
		
		List<MDCGroup> mdcGroupList = application.mdcSearch(MDCGroupAssembler.toEntity(dto));
		return InvokeResult.success(mdcGroupList);
	}

	@Override
	public InvokeResult findAllMDCGroup(IndexCalDTO dto) {
		
		//将时间格式化
	    dto.setDateFrom(DrgsIndex.formateDateFrom(dto.getDateFrom()));
	    dto.setDateTo(DrgsIndex.formateDateTo(dto.getDateTo()));
		List<MDCGroup> mdcGroupList = application.findAllMDCGroup(IndexCalAssembler.toEntity(dto));
		return InvokeResult.success(mdcGroupList);
	}

	@Override
	public InvokeResult queryVercode(MDCGroupDTO dto) {
		List<MDCGroup> verCodeList = application.queryVercode(MDCGroupAssembler.toEntity(dto));
		return InvokeResult.success(verCodeList);
	}

	@Override
	public List<Map<String,Object>> findAllMDC(MDCGroupDTO mdcDto) {
		return  application.findAllMDC(MDCGroupAssembler.toEntity(mdcDto));
	}
/**
 *  @Description：解析drg数据
 *  @Author：liuhongjun 
 *  @see com.dhcc.DRGsHosp.facade.MDCGroupFacade#drgFileupload(java.lang.String, java.lang.String)
 */
	@Override
	public InvokeResult drgFileupload(String filePath, String type,String verCode) {
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		if (".xls".equals(extension) || ".xlsx".equals(extension)) {
			try {
				Workbook workbook = null;
				Sheet sheet = null;
				Row row = null;
				Cell cell = null;
				try {
				if (extension.equals(".xls")) {
					workbook = new HSSFWorkbook(new FileInputStream(filePath));
					sheet = (HSSFSheet) workbook.getSheetAt(0);
				} else if (extension.equals(".xlsx")) {
					workbook = new XSSFWorkbook(new FileInputStream(filePath));
					sheet = (XSSFSheet) workbook.getSheetAt(0);
				} else {
					System.err.println("上传的文件不是有效的excel文件！");
				}
				}catch(Exception e) {
					LOGGER.error(e.getMessage());
				}
				int rowCnt = sheet.getLastRowNum();// 总行数
				// 循环每一行
				for (int j = 1; j <= rowCnt; j++) {
					row = sheet.getRow(j);
					String code="";
					String desc="";
					cell = row.getCell(0);
					if (cell != null) {
						code=cell.getStringCellValue();
					}
					cell = row.getCell(1);
					if (cell != null) {
						desc=cell.getStringCellValue();
					}
					if(code!=null) {
						if("MDC".equals(type)) {
							application.saveMdc(code,desc,verCode);
						}else if("ADRG".equals(type)) {
							String mdcCode="MDC"+code.substring(0, 1);
							application.saveAdrg(code,desc,mdcCode,verCode);
						}else {
							String adrgCode=code.substring(0, 3);
							application.saveDrg(code,desc,adrgCode,verCode);
						}
					}
				}
				/**
				 * 读取完数据以后删除upload下的所有文件
				 */
				File tempFile = new File(filePath);
				File[] tempList = tempFile.listFiles();
				if (tempFile.isFile()) {
					tempFile.delete();
				} else {
					for (int i = 0; i < tempList.length; i++) {
						tempList[i].delete();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return InvokeResult.failure(e.getMessage());
			}
		}
		return InvokeResult.success();
	}
}
